package org.foreveross.que.applicationImpl;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.util.Version;
import org.foreveross.que.entity.SayEntity;
import org.foreveross.que.entity.TopicEntity;
import org.foreveross.que.infra.base.constant.SysConstants;
import org.hibernate.search.jpa.FullTextEntityManager;
import org.hibernate.search.jpa.FullTextQuery;
import org.hibernate.search.jpa.Search;
import org.springframework.stereotype.Service;

import org.foreveross.que.application.FullTextApplication;
import org.foreveross.que.vo.IndexVo;
/**
 * 
 * @author lyq
 */
@Service
public class FullTextApplicationImpl implements FullTextApplication {

	@Inject
	@PersistenceContext(unitName="default")
	protected EntityManager entityManager;
	
	/**
	 *  全文搜索
	 * @param vo 页面vo
	 * @return
	 * @throws Exception
	 */
		public List fullTextSearch(IndexVo vo)
				throws Exception {
			final String[] fields = new String[] { "title", "subjectInfo",
					"replyInfo" }; // search on these fields
			BooleanClause.Occur[] flags = { BooleanClause.Occur.SHOULD,
					BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD };
			List results = new ArrayList();
			try {
				FullTextEntityManager fullTextEntityManager = Search
						.getFullTextEntityManager(entityManager);
				Analyzer analyzer = new com.chenlb.mmseg4j.analysis.ComplexAnalyzer();
				QueryParser parser = new MultiFieldQueryParser(Version.LUCENE_36,
						fields, analyzer);

				org.apache.lucene.search.Query query = MultiFieldQueryParser.parse(
						Version.LUCENE_36, vo.getContent(), fields, flags, analyzer);

				FullTextQuery fullTextQuery = fullTextEntityManager
						.createFullTextQuery(query, TopicEntity.class,
								SayEntity.class);

				fullTextQuery.setMaxResults(SysConstants.LUCENE_MAX_COUNT);
				int start = vo.getPageData().getPageIndex()<=0?0:(vo.getPageData().getPageIndex()-1)*vo.getPageData().getPageLen();
				fullTextQuery.setFirstResult(start);
				fullTextQuery.setMaxResults(start+vo.getPageData().getPageLen());
				Sort sort = new Sort();
				SortField field = new SortField("lastTime", 1);
				sort.setSort(field);
				fullTextQuery.setSort(sort);
				results = fullTextQuery.getResultList();
			} catch (Exception e) {
				throw new PersistenceException(e);
			}
			return results;
		}
}
